﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using FastBinarySerialization;

namespace SpeedTest
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Measuring speed of serializers this may take a few seconds:");
			Console.WriteLine();
			int iterations = 100 * 1000;

			SampleClass sample = new SampleClass()
			{
				Id = 10,
				Name = "John Doe",
				TimeStamp = DateTime.Now,
				Value = Math.PI
			};

			ProfileXmlSerializer(sample, iterations);
			ProfileBinaryFormatter(sample, iterations);
			ProfileFastBinarySerializer(sample, iterations);

			Console.WriteLine();
			Console.WriteLine("Press any key to continue");
			Console.ReadKey();
		}

		private static void ProfileXmlSerializer(SampleClass sample, int iterations)
		{
			Console.Write("XmlSerializer");
			Stopwatch sw = Stopwatch.StartNew();
			long streamLength = 0;
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(SampleClass));
			for (int i = 0; i < iterations; i++)
			{
				MemoryStream memStream = new MemoryStream();
				xmlSerializer.Serialize(memStream, sample);

				if (i == 0)
					streamLength = memStream.Position;

				memStream.Position = 0;
				object resultObj = xmlSerializer.Deserialize(memStream);
			}
			sw.Stop();
			Console.WriteLine(" duration " + sw.Elapsed.TotalMilliseconds + " ms with streamLength: " + streamLength);
		}
		private static void ProfileBinaryFormatter(SampleClass sample, int iterations)
		{
			Console.Write("BinaryFormatter");
			Stopwatch sw = Stopwatch.StartNew();
			long streamLength = 0;
			BinaryFormatter binFormatter = new BinaryFormatter();
			for (int i = 0; i < iterations; i++)
			{
				MemoryStream memStream = new MemoryStream();
				binFormatter.Serialize(memStream, sample);

				if (i == 0)
					streamLength = memStream.Position;

				memStream.Position = 0;
				object resultObj = binFormatter.Deserialize(memStream);
			}
			sw.Stop();
			Console.WriteLine(" duration " + sw.Elapsed.TotalMilliseconds + " ms with streamLength: " + streamLength);
		}
		private static void ProfileFastBinarySerializer(SampleClass sample, int iterations)
		{
			Console.Write("FastBinarySerializer");
			Stopwatch sw = Stopwatch.StartNew();
			long streamLength = 0;
			for (int i = 0; i < iterations; i++)
			{
				MemoryStream memStream = new MemoryStream();
				FastBinarySerializer.Serialize(memStream, sample);

				if (i == 0)
					streamLength = memStream.Position;

				memStream.Position = 0;
				object resultObj = FastBinarySerializer.Deserialize(memStream);
			}
			sw.Stop();
			Console.WriteLine(" duration " + sw.Elapsed.TotalMilliseconds + " ms with streamLength: " + streamLength);
		}
	}
}
